package mdm.led.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import mdm.led.common.LocalConfig;
import mdm.led.dao.SysBackupMapper;
import mdm.led.entity.SysBackup;
import mdm.led.service.ISystemService;
import mdm.led.util.DateUtil;
import mdm.led.util.MySqlDBUtil;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("iSystemService")
public class SystemServiceImpl implements ISystemService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SystemServiceImpl.class);

    private final LocalConfig localConfig;
    private final SysBackupMapper sysBackupMapper;

    @Autowired
    public SystemServiceImpl(LocalConfig localConfig,
                             SysBackupMapper sysBackupMapper) {
        this.localConfig = localConfig;
        this.sysBackupMapper = sysBackupMapper;
    }

    @Override
    public void backup(Integer userId) throws Exception {
        String fileName = "backup_" + UUID.randomUUID() + ".sql";
        String filePath = localConfig.getSystem_backup() + fileName;

        LOGGER.info("----------------filepath:{}", filePath);

        String username = localConfig.getUsername();
        String password = localConfig.getPassword();
        String database = localConfig.getDatabase();
        String mysqlPath = localConfig.getMysql_path();

        MySqlDBUtil.backupDB(username, password, database, filePath);
        short state = 1;
        SysBackup sysBackup = new SysBackup();
        sysBackup.setcUserId(userId);
        sysBackup.setcBackupFile(fileName);
        sysBackup.setState(state);
        sysBackupMapper.insertSelective(sysBackup);
    }

    @Override
    public SysBackup selectByBackupTime(Date date) throws Exception {
        return sysBackupMapper.selectByBackupDate(date);
    }

    @Override
    public SysBackup selectByPrimaryKey(Integer backupId) throws Exception {
        return sysBackupMapper.selectByPrimaryKey(backupId);
    }

    @Override
    public void removeById(Integer backupId) throws Exception {
        sysBackupMapper.removeById(backupId);
    }

    @Override
    public List<SysBackup> selectByCondition(SysBackup sysBackup) throws Exception {
        if (StringUtils.isNotEmpty(sysBackup.getEndDate())) {
            sysBackup.setEndDate(DateUtil.addDate(sysBackup.getEndDate(), 1));
        }
        List<SysBackup> sysBackups = sysBackupMapper.selectByCondition(sysBackup);
        return sysBackups;
    }

}
